<?php

namespace app\common\service\live;

use app\admin\model\Live\LiveSpeak;
use app\admin\model\Live\LiveUserLog;
use app\common\service\BaseService;
use app\validate\Live\LiveSpeakCheck;
use Symfony\Component\VarDumper\Dumper\DataDumperInterface;
use think\facade\Cache;
use function AlibabaCloud\Client\envNotEmpty;

class LiveSpeakService extends BaseService
{
    //校验用户是否被禁言
    public static function userVerify($userId)
    {
        $userLog = new LiveUserLog();
        $noSpeakTime=$userLog->getUserNoSpeakTime($userId);
        $time =  time()-$noSpeakTime['no_speaking_time'];
        if ($time<0){
            return self::fail('用户禁止发言');
        }else{
            return true;
        }
    }

    /**保存弹幕
     * Author:William
     * @param array $params
     * @return array|string|true|void
     */
    public static function save(array $params =[])
    {
        $res = self::validateFail(LiveSpeakCheck::class, $params);
        if (!empty($res)) {
            return $res;
        }
        //同时存入mysql 和 redis
        $redisRes = self::addRedisSpeak($params);
        $res = LiveSpeak::create($params);
        if ($res !== false && $redisRes !== null) {
            return self::success('添加弹幕成功');
        } else {
            return self::fail('添加弹幕失败');
        }
    }

    //redis存储弹幕的方法
    public static function addRedisSpeak(array $params)
    {
        if (empty($params)) {
            return false;
        }
        if (!isset($params)) {
            return false;
        }
        $redis = Cache::store('redis');
        $redis->select(3);
        $listKey = config('setting.live.listKey');
        $red = $redis->lpush($listKey, $params['content']);
        return $red;
    }

    //redis拉取弹幕的
    public static function getRedisSpeak(string $listKey)
    {
        $redis = Cache::store('redis');
        $redis->select(3);
        $res = $redis->lrange($listKey,0,5);
        $arr = [];
        foreach ($res as $key => $value){
            $arr [] = ['msg'=>$value,'time'=>''];
        }
        return self::success('拉取成功',$arr);
    }

}